import 'package:flutter/material.dart';
import 'FeaturesItem.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../MessagePage/MessageDetailPage.dart';
import '../widgets/AppColors.dart';
import '../../Tools/ToolsLocalStorage.dart';
import '../CentrePage/Device/BreakdownDetailPage.dart';

class SettingMessagePage extends StatefulWidget {
  const SettingMessagePage({super.key});

  @override
  State<SettingMessagePage> createState() => _SettingMessagePageState();
}

class _SettingMessagePageState extends State<SettingMessagePage>
    with SingleTickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  late TabController _tabController;
  List<dynamic> listData = [];
  List<dynamic> malfunctions = [];
  List<dynamic> notices = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _tabController = TabController(length: 3, vsync: this);
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    _loadData();
    // });
  }

  Future<void> _loadData() async {
    //设备故障
    try {
      final result = await _fetchData();
      if (result['rows'] != null) {
        setState(() {
          malfunctions = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }

    //通知
    try {
      final result = await _fetchNoteData();
      if (result != null && result['rows'] != null) {
        setState(() {
          listData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }

    try {
      final result = await _fetchDataN();
      if (result != null && result['data'] != null) {
        setState(() {
          notices = (result['data']['objectList'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/malfunctiontype/selecList?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('steeloutday Failed to load data');
      }
    } catch (e) {
      print('steeloutday Error in _fetchData: $e');
      rethrow;
    }
  }

  Future<Map<String, dynamic>?> _fetchNoteData() async {
    try {
      final response = await _networkService.get('/system/notice/list');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  //资讯消息
  Future<Map<String, dynamic>?> _fetchDataN() async {
    try {
      final response = await _networkService.post(
        '/miniApp/officialAccount/getContentList',
        data: {
          'pageIndex': 1,
          'pageSize': 50,
        },
      ); //  system/notice/list
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('我的消息'),
        backgroundColor: Colors.transparent,
        foregroundColor: AppColors.textPrimary,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48), // Adjust height as needed
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.transparent, // Set the background color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: TabBar(
              isScrollable: false,
              indicatorColor: Colors.blue,
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.only(right: 50, left: 50),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor: TDTheme.of(context).grayColor12,
              unselectedLabelColor: TDTheme.of(context).grayColor8,
              labelStyle:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              controller: _tabController,
              tabs: [
                Tab(
                    child: Text("故障消息",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("资讯消息",
                        style: TextStyle(color: AppColors.textPrimary))),
                Tab(
                    child: Text("通知",
                        style: TextStyle(color: AppColors.textPrimary))),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ListView(
            children: [
              ListView.builder(
                itemCount: malfunctions.length,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 0.0),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const BreakdownDetailPage(),
                          ),
                        );
                      },
                      child:
                          FeaturesItem(pageType: 0, data: malfunctions[index]),
                    ),
                  );
                },
              ),
            ],
          ),
          ListView(
            children: [
              ListView.builder(
                itemCount: notices.length,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 0.0),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  // MessageDetailPage(noticeId: 1),
                                  MessageDetailPage(
                                      title: notices[index]['title'],
                                      content: notices[index]['content'])),
                        );
                      },
                      child: FeaturesItem(pageType: 1, data: notices[index]),
                    ),
                  );
                },
              ),
            ],
          ),
          ListView(
            children: [
              ListView.builder(
                itemCount: listData.length,
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 0.0),
                    child: GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                // MessageDetailPage(noticeId: 1),
                                MessageDetailPage(
                                    title: listData[index]['title'],
                                    content: listData[index]['content']),
                          ),
                        );
                      },
                      child: FeaturesItem(pageType: 2, data: listData[index]),
                    ),
                  );
                },
              ),
            ],
          ),
        ],
      ),
    );
  }
}
